package cn.zwz.data.controller;

import cn.zwz.basics.baseVo.Result;
import cn.zwz.basics.utils.ResultUtil;
import cn.zwz.data.entity.CartEntity;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j // 日志
@Api(tags = "购物车接口") // 接口文档
@RestController
@RequestMapping("/zwz/cart")
@Transactional // 开启事务
public class CartController {
    //创建数据库连接池
    String url = "jdbc:mysql://localhost:3306/s001?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
    String username = "root";
    String password = "";
    DataSource dataSource = new DriverManagerDataSource(url, username, password);
    //创建JDBCTemplate
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public Result page(@RequestParam Map<String, Object> params) {
//        if(!request.getSession().getAttribute("role").toString().equals("管理员")) {
//            cart.setUserid((Long)request.getSession().getAttribute("userId"));
//        }
//        EntityWrapper<CartEntity> ew = new EntityWrapper<CartEntity>();
//        PageUtils page = cartService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, cart), params), params));
//
//        return R.ok().put("data", page);
        return null;
    }

    /**
     * 前端列表
     */

    @RequestMapping("/list")
    public Result<List<CartEntity>> page(@RequestParam String page, @RequestParam String limit, @RequestParam String userid) {
        int pageNum = Integer.parseInt(page);
        int pageSize = Integer.parseInt(limit);
        int offset = (pageNum - 1) * pageSize;
        if (userid == null || userid.equals("")) {
            return ResultUtil.error("用户id不能为空");
        }
        String sql = "select * from a_cart where userid = ? limit ?,?";
        List<CartEntity> cartList = jdbcTemplate.query(sql, new Object[]{userid, offset, pageSize}, new BeanPropertyRowMapper<>(CartEntity.class));
        System.err.println(cartList);
        return new ResultUtil<List<CartEntity>>().setData(cartList);
    }

    /**
     * 列表
     */
//    查询购物车是否有该商品，根据goodid
    @GetMapping("/queryListByGoodId")
    public Result list(@RequestParam String goodid, @RequestParam String userid) {
        System.err.println("goodid:" + goodid);
        if (goodid == null || goodid.equals("")) {
            return ResultUtil.error("商品id不能为空");
        }
        if (userid == null || userid.equals("")) {
            return ResultUtil.error("用户id不能为空");
        }
        String sql = "select * from a_cart where goodid = ? and userid = ?";
        List<CartEntity> cartList = jdbcTemplate.query(sql, new Object[]{goodid, userid}, new BeanPropertyRowMapper<>(CartEntity.class));
        return new ResultUtil<List<CartEntity>>().setData(cartList);
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public Result query(CartEntity cart) {
//        EntityWrapper< CartEntity> ew = new EntityWrapper< CartEntity>();
//        ew.allEq(MPUtil.allEQMapPre( cart, "cart"));
//        CartView cartView =  cartService.selectView(ew);
//        return R.ok("查询购物车表成功").put("data", cartView);
        return null;
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
//        CartEntity cart = cartService.selectById(id);
//        return R.ok().put("data", cart);
        return null;
    }

    /**
     * 前端详情
     */
    @RequestMapping("/detail/{id}")
    public Result detail(@PathVariable("id") Long id) {
//        CartEntity cart = cartService.selectById(id);
//        return R.ok().put("data", cart);
        return null;
    }


    /**
     * 后端保存
     */
    @GetMapping("/save")
    public Result save(@RequestParam String tablename, @RequestParam String goodid, @RequestParam String goodname, @RequestParam String picture, @RequestParam Integer buynumber, @RequestParam Float price, @RequestParam Float discountprice,
                       @RequestParam String userid) {
        CartEntity cart = new CartEntity();
        cart.setTablename(tablename);
        cart.setGoodid(goodid);
        cart.setGoodname(goodname);
        cart.setPicture(picture);
        cart.setBuynumber(buynumber);
        cart.setPrice(price);
        cart.setDiscountprice(discountprice);
        cart.setAddtime(new Date());
//        静态工厂valueOf(double)通常是更好的选择，因为它可能会产生明显更好的空间和时间性能
        cart.setId(new Date().getTime() + Double.valueOf(Math.floor(Math.random() * 1000)).longValue());
        cart.setUserid(Long.valueOf(userid)); // 获取当前登录用户id
        String sql = "insert into `a_cart` (id, tablename,goodid,goodname,picture,buynumber,userid,price,discountprice,addtime) values (?,?,?,?,?,?,?,?,?,?)";
        int update = jdbcTemplate.update(sql, cart.getId(), cart.getTablename(), cart.getGoodid(), cart.getGoodname(), cart.getPicture(), cart.getBuynumber(), cart.getUserid(), cart.getPrice(), cart.getDiscountprice(), cart.getAddtime());
        if (update > 0) {
            return new ResultUtil().setData(cart.getId(), "添加购物车成功");
        } else {
            return new ResultUtil().setErrorMsg(500, "添加购物车失败");
        }
    }

    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public Result add(@RequestBody CartEntity cart, HttpServletRequest request) {
//        cart.setId(new Date().getTime()+new Double(Math.floor(Math.random()*1000)).longValue());
//        //ValidatorUtils.validateEntity(cart);
//        cartService.insert(cart);
//        return R.ok();
        return null;
    }

    /**
     * 修改
     */
    @GetMapping("/update")
    public Result update(@RequestParam String userid, @RequestParam String goodid, @RequestParam Integer buynumber) {
        if (userid == null || userid.equals("")) {
            return ResultUtil.error("用户id不能为空");
        }
        if (goodid == null || goodid.equals("")) {
            return ResultUtil.error("商品id不能为空");
        }
        if (buynumber == null || buynumber.equals("")) {
            return ResultUtil.error("购买数量不能为空");
        }
//        buynumber转成int类型
        buynumber = Integer.parseInt(buynumber.toString());
        String sql = "update a_cart set buynumber = ? where userid = ? and goodid = ?";
        int update = jdbcTemplate.update(sql, buynumber, userid, goodid);
        if (update > 0) {
            return new ResultUtil().setSuccessMsg("修改购物车成功");
        } else {
            return new ResultUtil().setErrorMsg(500, "修改购物车失败");
        }
    }


    /**
     * 删除购物车
     */
    @PostMapping("/deleteIDS")
    public Result delete(@RequestBody Long[] ids) {
        if (ids == null || ids.length == 0) {
            return new ResultUtil<>().setErrorMsg("ID数组不能为空");
        }

        // 将数组中的值连接成一个逗号分隔的字符串
        String idsString = Arrays.stream(ids)
                .map(String::valueOf)
                .collect(Collectors.joining(","));

        String sql = "DELETE FROM a_cart WHERE `id` IN (" + idsString + ")";
        int update = jdbcTemplate.update(sql);

        if (update > 0) {
            return new ResultUtil<>().setData(null);
        } else {
            return new ResultUtil<>().setErrorMsg("删除购物车失败");
        }
    }


    @RequestMapping("/detail/delete")
    public Result detail(@RequestParam String userid, @RequestParam String id) {
        if (userid == null || userid.equals("")) {
            return ResultUtil.error("用户ID不能为空");
        }
        if (id == null || id.equals("")) {
            return ResultUtil.error("购物车ID不能为空");
        }
        String sql = "delete from a_cart where `userid` = ? and `id` = ?";
        int update = jdbcTemplate.update(sql, userid, id);
        if (update > 0) {
            return new ResultUtil().setSuccessMsg("删除商品成功");
        } else {
            return new ResultUtil().setErrorMsg(500, "删除商品失败");
        }
    }

    /**
     * 提醒接口
     */
    @RequestMapping("/remind/{columnName}/{type}")
    public Result remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request,
                              @PathVariable("type") String type, @RequestParam Map<String, Object> map) {
        return null;
    }


}
